//
//  FR_SearchRecordViewController.m
//  FaceRecognition
//
//  Created by Sylar on 2016/12/1.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "FR_SearchRecordViewController.h"
#import "FR_StudentRecordList_ViewController.h"
#import "SearchResultCell.h"
#import "FR_His_SearchBar.h"
@interface FR_SearchRecordViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) FR_His_SearchBar *searchBar;
@property (nonatomic, strong) UITableView *resultTabel;
@property (nonatomic, strong) UILabel  *nostuLabel;

@property (nonatomic, strong) NSMutableArray *studentsArr;
@property (nonatomic, strong) NSMutableArray *resultArr;
@property (nonatomic, copy) NSString *searchText;


@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;

@end

@implementation FR_SearchRecordViewController

- (void)loadView {
   
   [super loadView];
   
   self.navBar.backImg.hidden = YES;
   self.navBar.backButton.hidden = YES;
   
   self.navBar.rightButton.hidden = NO;
   self.navBar.rightButton.frame = CGRectMake(SCREENWIDTH - 45 - 7, SafeAreaTopHeight - 29 - 7.5, 45, 29);
   [self.navBar.rightButton setTitle:@"取消" forState:UIControlStateNormal];
   [self.navBar.rightButton.titleLabel setFont:[UIFont systemFontOfSize:17]];
   
   [self.navBar.rightButton setTitleColor:colorFromHex(@"3b3b3b") forState:UIControlStateNormal];
   [self.navBar.rightButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
   [self.navBar.rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
   
   [self.navBar.rightButton addTarget:self action:@selector(cancleAction) forControlEvents:UIControlEventTouchUpInside];
   [self.navBar.rightButton sizeToFit];
   
   
   self.searchBar = [[FR_His_SearchBar alloc]initWithFrame:CGRectMake(7,SafeAreaTopHeight - 29 - 7.5, self.view.width-75+14, 29)];
   //[self.searchBar canResignFirstResponder];
   [self.searchBar setShowsCancelButton:NO];
   
   //[self.searchBar setSearchTextPositionAdjustment:UIOffsetMake(-8, 0)];
   self.searchBar.delegate = self;
   if (self.searchType == 0) {
      [self.searchBar setPlaceholder:@"搜索班级宝宝识别记录"];
   }else {
      [self.searchBar setPlaceholder:@"搜索员工识别记录"];
   }
   
   //[self.searchBar setTintColor:[UIColor whiteColor]];
   [self.searchBar setBackgroundColor:[UIColor whiteColor]];
   [self.searchBar setBackgroundImage:[Utils imageWithColor:[UIColor whiteColor] size:self.searchBar.bounds.size]];
   //    self.searchBar.layer.cornerRadius = 5;
   //    self.searchBar.layer.borderWidth = 1;
   //    self.searchBar.layer.borderColor = [UIColor lightGrayColor].CGColor;
   [self.searchBar setImage:[UIImage imageNamed:@"search_head_"]forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
   
   UITextField *searchTextField = nil;
   self.searchBar.barTintColor = [UIColor whiteColor];
   searchTextField = [[[self.searchBar.subviews firstObject] subviews] lastObject];
   //    [self.searchBar setValue:searchTextField forKey:@"_searchField"];
   
   //这里改变输入框边框的颜色和边框的宽度
   searchTextField.layer.borderWidth = 1;
   searchTextField.font = [UIFont systemFontOfSize:13];
   searchTextField.layer.borderColor = [UIColor lightGrayColor].CGColor;
   searchTextField.layer.cornerRadius = 5.0f;
   
   //self.searchBar.layer.cornerRadius = 8;
   //    self.searchBar.layer.masksToBounds = YES;
   
   
   [self.navBar addSubview:self.searchBar];
   
   
}

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view.
   [self.view setBackgroundColor:colorFromHex(@"#F5F8FA")];
   
   [self.view addSubview:self.resultTabel];
   
   
   [self Java_StudentsByClassID];
   
   [self.searchBar becomeFirstResponder];
   
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

- (void)dealloc {
   
   
}

#pragma mark - Request

- (void)Java_StudentsByClassID {
   NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
   [paramDic setObject:@"-1" forKey:@"photocounts"];
   [paramDic setObject:@"1000" forKey:@"pagesize"];
   [paramDic setObject:@"1" forKey:@"pageno"];
   
   if (self.searchType == 0) {
      [paramDic setObject:self.classID forKey:@"classid"];
      
   }else {
      
      [paramDic setObject:[NSString stringWithFormat:@"%lld",[SYAccountTool ShareAccount].account.schoolManage] forKey:@"scid"];
      [paramDic setObject:self.departmentid forKey:@"departmentid"];
   }
   
   NSString *methodStr = self.searchType == 0 ? @"api/getClassStudentList":@"api/getSchoolUserList";
   
   [Utils Java_get:methodStr parameters:paramDic success:^(NSInteger recode, id jsonObject) {
      
      NSArray *arr = [jsonObject objectForKey:@"re_data"];
      
      if (arr.count > 0) {
         self.studentsArr = [[NSMutableArray alloc]init];
         
         for (NSDictionary *dic in arr) {
            
            FR_StudentRecode_Model *model = [FR_StudentRecode_Model mj_objectWithKeyValues:dic];
            
            [self.studentsArr addObject:model];
         }
      }
      
   } failure:^(NSInteger recode, NSError *error) {
      
      [self showHint:error.localizedDescription];
      
   }];
}

- (void)getStudentsByClassID {
   
   NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
   if (self.searchType == 0) {
      [paramDic setObject:self.classID forKey:@"classid"];
      [paramDic setObject:@"api_classstudent_listbyface" forKey:@"method"];
      
   }else {
      //[paramDic setObject:self.classID forKey:@"departmentid"];
      [paramDic setObject:@"api_schoolteacher_listbyface" forKey:@"method"];
      [paramDic setObject:[NSString stringWithFormat:@"%lld",[SYAccountTool ShareAccount].account.schoolManage] forKey:@"scid"];
   }
   [paramDic setObject:@"-1" forKey:@"photocounts"];
   [paramDic setObject:@"1000" forKey:@"pagesize"];
   [paramDic setObject:@"1" forKey:@"pageno"];
   
   
   [Utils get:nil parameters:paramDic success:^(NSInteger recode, id jsonObject) {
      
      NSArray *arr = [jsonObject objectForKey:@"re_data"];
      
      
      if (arr.count > 0) {
         self.studentsArr = [[NSMutableArray alloc]init];
         
         for (NSDictionary *dic in arr) {
            
            FR_StudentRecode_Model *model = [FR_StudentRecode_Model mj_objectWithKeyValues:dic];
            
            [self.studentsArr addObject:model];
         }
      }
      
   } failure:^(NSInteger recode, NSError *error) {
      
      
   }];
   
}

#pragma mark - Method

-(void)didTapAnywhere:(UITapGestureRecognizer *)recognizer
{
   [self.searchBar resignFirstResponder];
}

#pragma mark - Action

- (void)cancleAction {
   
   [self.navigationController popViewControllerAnimated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
   
   [self.searchBar resignFirstResponder];
}

#pragma mark - SearchDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
   self.searchText = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
   
   NSPredicate *preicate;
   
   if (self.searchType == 0) {
      preicate = [NSPredicate predicateWithFormat:@"self.studentname contains[c] %@", self.searchText];
   }else {
      preicate = [NSPredicate predicateWithFormat:@"self.username contains[c] %@", self.searchText];
   }
   if (self.resultArr!= nil) {
      [self.resultArr removeAllObjects];
   }
   //过滤数据
   self.resultArr= [NSMutableArray arrayWithArray:[self.studentsArr filteredArrayUsingPredicate:preicate]];
   if (self.searchText.length == 0) {
      [self.nostuLabel setHidden:YES];
   }else {
      [self.nostuLabel setHidden:self.resultArr.count == 0?NO:YES];
   }
   
   //刷新表格
   [self.resultTabel reloadData];
   //[_searchBar resignFirstResponder];
   
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
   
   NSLog(@"%@",self.searchText);
   
   NSPredicate *preicate;
   
   if (self.searchType == 0) {
      preicate = [NSPredicate predicateWithFormat:@"self.studentname contains[c] %@", self.searchText];
   }else {
      preicate = [NSPredicate predicateWithFormat:@"self.username contains[c] %@", self.searchText];
   }
   
   
   if (self.resultArr!= nil) {
      [self.resultArr removeAllObjects];
   }
   //过滤数据
   self.resultArr= [NSMutableArray arrayWithArray:[self.studentsArr filteredArrayUsingPredicate:preicate]];
   
   if (self.searchText.length == 0) {
      [self.nostuLabel setHidden:YES];
   }else {
      [self.nostuLabel setHidden:self.resultArr.count == 0?NO:YES];
   }
   //刷新表格
   [self.resultTabel reloadData];
   [_searchBar resignFirstResponder];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [self.resultArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
   SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchIdentifier"];
   
   if (cell == nil) {
      cell = [[SearchResultCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"searchIdentifier"];
      cell.selectionStyle = UITableViewCellSelectionStyleNone;
      
      UIView *line = [[UIView alloc]initWithFrame:CGRectMake(15, 57.5, SCREENWIDTH, 0.5)];
      [line setBackgroundColor:colorFromHex(@"#DEDEDE")];
      if (indexPath.row == self.resultArr.count - 1) {
         [line setX:0];
      }
      [cell.contentView addSubview:line];
   }
   
   FR_StudentRecode_Model *model = [self.resultArr objectAtIndex:indexPath.row];
   
   [cell creatCell:model];
   NSMutableArray *arry;
   NSMutableAttributedString *attributedStr;
   if (self.searchType == 0) {
      arry=[[NSMutableArray alloc]initWithArray:[Utils  getRangeStr:model.studentname findText:self.searchText]];
      
      attributedStr = [[NSMutableAttributedString alloc] initWithString:model.studentname];
   }else {
      arry=[[NSMutableArray alloc]initWithArray:[Utils  getRangeStr:model.username findText:self.searchText]];
      
      attributedStr = [[NSMutableAttributedString alloc] initWithString:model.username];
   }
   
   for (int i=0; i<arry.count; i++) {
      
      NSMutableAttributedString *attributedStr01 = [[NSMutableAttributedString alloc] initWithAttributedString:attributedStr];
      NSRange  range=NSMakeRange([[arry objectAtIndex:i] intValue], self.searchText.length);
      
      [attributedStr01 addAttribute: NSForegroundColorAttributeName
                              value: DEFAULTCOLOR
                              range: range];
      attributedStr=attributedStr01;
   }
   cell.nameLabel.attributedText=attributedStr;
   
   return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
   FR_StudentRecordList_ViewController *listVC = [[FR_StudentRecordList_ViewController alloc]init];
   FR_StudentRecode_Model *model = [self.resultArr objectAtIndex:indexPath.row];
   listVC.faceuserid = [NSString stringWithFormat:@"%ld",(long)model.faceuserid];
   
   if (self.searchType == 0) {
      listVC.userid = [NSString stringWithFormat:@"%ld",(long)model.studentid];
      listVC.classId = [NSString stringWithFormat:@"%ld",(long)model.classid];
   }else if (self.searchType == 1) {
      listVC.userid = [NSString stringWithFormat:@"%ld",(long)model.userid];
      listVC.scid = [NSString stringWithFormat:@"%ld",(long)model.scid];
   }
   
   listVC.recordType = self.searchType;
   [self.navigationController pushViewController:listVC animated:YES];
   
}

#pragma mark - Get

- (UITableView *)resultTabel {
   
   if (_resultTabel == nil) {
      
      _resultTabel = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight - SafeAreaBottomHeight) style:(UITableViewStylePlain)];
      _resultTabel.delegate = self;
      _resultTabel.dataSource = self;
      _resultTabel.rowHeight = 58;
      _resultTabel.separatorStyle = UITableViewCellSeparatorStyleNone;
      _resultTabel.backgroundColor = colorFromHex(@"#F5F8FA");
      
      self.nostuLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, SCREENWIDTH, 15)];
      [self.nostuLabel setFont:[UIFont systemFontOfSize:14]];
      [self.nostuLabel setText:@"暂无信息"];
      [self.nostuLabel setTextColor:[UIColor colorWithHexString:@"#979797"]];
      self.nostuLabel.textAlignment = NSTextAlignmentCenter;
      self.nostuLabel.hidden = YES;
      
      [_resultTabel addSubview:self.nostuLabel];
      
   }
   
   return _resultTabel;
}

- (UITapGestureRecognizer *)tapGestureRecognizer
{
   if (!_tapGestureRecognizer) {
      _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)];
   }
   return _tapGestureRecognizer;
}

@end
